<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Work Group</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/student-system.css" />
	<link rel="stylesheet" type="text/css" href="css/menubar.css" />
	<link rel="stylesheet" type="text/css" href="css/frame.css" />
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script type="text/javascript">
		function add_workgroup() {
			document.location.href = "admin_workgroup_add.jsp";
		}
		
		function deleteButton(id) {
			var workgroupId = (document.getElementById('workgroupId'+ id)).value;
			var workgroup = (document.getElementById('workgroupName' + id)).innerHTML.trim();
			var department = (document.getElementById('departmentName' + id)).innerHTML.trim();
						
			if (confirm("คุณต้องการจะลบข้อมูลหน่วยงาน" + workgroup + "ของภาควิชา " + department) == true) {
				/* AJAX */
				var xmlhttp;
				
				if(window.XMLHttpRequest) {
					// code for IE7+, Firefox, Chrome, Opera, Safari
					xmlhttp = new XMLHttpRequest();
				}
				else {
					// code for IE6, IE5
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				
				xmlhttp.onreadystatechange = function() {
					if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						var result = xmlhttp.responseText;

						if(result == "success") {
							window.location.reload();
							alert("สำเร็จ");////////test///////
						}
						else if(result == "fail") {
							alert("ไม่สามารถลบหน่วยงาน " + workgroup + "ของภาควิชา " + department+" ได้ เนื่องจากหน่วยงานนี้มีการใช้งานอยู่");////////test///////
						}
						else {
							alert("ไม่สามารถลบข้อมูลได้");////////test///////
						}
					}
				}
				
				xmlhttp.open("POST", "admin_workgroup_delete.jsp?workgroupId="+workgroupId, true);
				xmlhttp.send();
		    } else {

		    }
			
		}
	</script>
</head>
<body>

<%
	// get session
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
	
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps );
	
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	// find workgroup in database
	List<Workgroup> workgroup = new ArrayList<Workgroup>();
	
	try {			   
		ResultSet rs = connect.createStatement().executeQuery("SELECT W.workgroup_name, W.workgroup_id, D.department_name_th, D.department_id " 
				+ " FROM department D, workgroup W " 
				+ " WHERE W.department_id=D.department_id "
				+ " ORDER BY D.department_name_th, W.workgroup_name");
		
		while(rs.next()) {			
			Workgroup work = new Workgroup();
			
			work.setDepartmentId(Integer.parseInt(rs.getString("department_id")));
			work.setDepartmentNameTH(rs.getString("department_name_th"));
			work.setWorkgroupId(Integer.parseInt(rs.getString("workgroup_id")));
			work.setWorkgroupName(rs.getString("workgroup_name"));
			
			workgroup.add(work);
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	connect.close();
%>

	<div id="page-wrap">
			<div id="inside">
				<table border="0">
					<tr style="font-size:24px">
						<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
							<div id="header_banner-2"></div>
						</td>
						
						<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
							<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
							<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
						</td>
					</tr>
				</table>
				
				<ul id="drop-nav">
			        <li><a href="admin_home.jsp">หน้าแรก</a> </li>
			        
			        <li>
			            <span><a>องค์กร &nbsp; &#9662;</a></span>
			            <ul>
			                <li><a href="admin_department.jsp">ภาควิชา</a></li>
			                <li><a href="admin_workgroup.jsp">หน่วยงาน</a></li>
			            </ul>
			        </li>
			        <li><a href="admin_role.jsp">หน้าที่</a></li>
			        <li><a href="admin_account.jsp">บัญชีผู้ใช้</a></li>
			        <li>
			        	<a>บุคคล &nbsp; &#9662;</a>
			        	<ul>
			                <li><a href="admin_lecturer.jsp">อาจารย์</a></li>
			                <li><a href="admin_employee.jsp">บุคลากร</a></li>
			            </ul>
			        </li>
			        <li><a href="admin_entrance.jsp">ระบบเข้าศึกษา</a></li>
			        <li><a href="admin_status.jsp">สถานะของนักศึกษา</a></li>
			        <li>
			        	<a href="">ตำแหน่ง &nbsp; &#9662;</a>
			        	<ul>
			                <li><a href="admin_educate_position.jsp">ตำแหน่งทางวิชาการ</a></li>
			                <li><a href="admin_management_position.jsp">ตำแหน่งบริหาร</a></li>
			            </ul>
			        </li>
			    </ul>
		        
						<div id="main-content-ac">
													
							<br/><br/><br/><br/>
							
							<table style="border: 0px">
								<tr style="border: 0px">
									<td style="border: 0px">
										<div class="imageFrame">หน่วยงาน</div>
									</td>
									<td style="border: 0px">
										<div style="margin-top: 30px; margin-left: 20px; cursor: pointer;">
											<span title="เพิ่มข้อมูล">
												<img src="image/add_icon.png" width="40px" height="40px" onclick="add_workgroup()">
											</span>	
										</div>
									</td>
								</tr>
							</table>
							
							<br/><br/><br/><br/>
							<center>
								<div class="CSSTableGenerator">
									<table  border="1">
									  <tr style="font-size:24px">
									  	<td>&nbsp;</td>
										<td><center><strong>Work Group</strong></center></td>
										<td><center><strong>Department</strong></center></td>
										<td>&nbsp;</td>
										<td>&nbsp;</td>
									  </tr>
									  
								 
<%
				int workgroupCount = 1;
				for(Workgroup wg : workgroup) {

%> 
									  <tr style="font-size:20px" id="workgroup<%=workgroupCount%>">
									  	<form id="form<%=workgroupCount%>" name="form<%=workgroupCount%>" method="post" action="admin_workgroup_edit.jsp">
									  	
									  		<input type="hidden" id="workgroupId" name="workgroupId" value="<%=wg.getWorkgroupId()%>" />
									  		<input type="hidden" id="workgroupId<%=workgroupCount%>" name="workgroupId<%=workgroupCount%>" value="<%=wg.getWorkgroupId()%>" />
											<td id="workgroupCount<%=workgroupCount%>" name="workgroupCount<%=workgroupCount%>" align="center">
												<%=workgroupCount %>
											</td>
											
											<input type="hidden" id="workgroupName" name="workgroupName" value="<%=wg.getWorkgroupName()%>" />
											<td id="workgroupName<%=workgroupCount%>" name="workgroup<%=workgroupCount%>" align="center">
												<%=wg.getWorkgroupName()%>
											</td>
											
											<input type="hidden" id="departmentId" name="departmentId" value="<%=wg.getDepartmentId()%>" />
											<input type="hidden" id="departmentName" name="departmentName" value="<%=wg.getDepartmentNameTH()%>" />
											<td id="departmentName<%=workgroupCount%>" name="department<%=workgroupCount%>" align="center">
								<%
													if(wg.getDepartmentId() == 0) {
														out.print("-");
													}
													else {													
														out.print(wg.getDepartmentNameTH());
													}
								%>
													
											</td>
											
											<td>
												<center><span title="แก้ไขข้อมูล">
													<input type="image" src="image/edit_icon.png" height="30px" width="30px" />
												</span></center>
											</td>
										</form>
											<td>
												<center><span title="ลบข้อมูล">
													<input type="image" src="image/delete_icon.png" height="30px" width="30px"  onclick="deleteButton('<%=workgroupCount%>')" />
												</span></center>
											</td>
									  </tr>
<%
						workgroupCount++;
				}
				
%>				
									</table>
								</div>
							</center>
								<br><br><br>

					<div style="clear: both;"></div>
						<div id="footer"></div>
			</div>		
						<div style="clear: both;"></div>		
    </div>

</body>
</html>